<template>
  <a-modal
    v-model:open="visible"
    title="Verify Your Email"
    :closable="false"
    :maskClosable="false"
    :footer="null"
    width="450px"
    class="email-verification-modal"
  >
    <div class="email-verification">
      <div class="description">
        <div class="icon-container">
          <!-- <a-icon-mail class="email-icon" /> -->
        </div>
        <h3 class="title">Email Verification</h3>
        <p class="desc-text">To ensure your account security, please verify your email address. After verification, you will receive an exclusive invitation code and user points reward.</p>
      </div>
      
      <div class="verification-form">
        <!-- 显示当前邮箱 -->
        <a-form layout="vertical">
          <a-form-item label="Your Email Address">
            <a-input 
              v-model:value="userEmail" 
              disabled 
              class="email-input"
              prefix-icon="mail"
            />
          </a-form-item>
          
          <!-- Verification code input -->
          <a-form-item label="Verification Code">
            <a-row :gutter="12">
              <a-col :span="16">
                <a-input 
                  v-model:value="verificationCode" 
                  placeholder="Enter email verification code" 
                  class="code-input"
                />
              </a-col>
              <a-col :span="8">
                <a-button 
                  type="primary" 
                  :disabled="isSending || countdown > 0" 
                  @click="sendVerificationCode"
                  block
                  class="send-code-btn"
                >
                  {{ countdown > 0 ? `${countdown}s` : 'Get Code' }}
                </a-button>
              </a-col>
            </a-row>
          </a-form-item>
          
          <!-- 提交按钮 -->
          <a-form-item>
            <a-button 
              type="primary" 
              @click="verifyEmail" 
              :loading="isVerifying"
              block
              class="verify-btn"
            >
              Verify Email
            </a-button>
          </a-form-item>
          
          <!-- 关闭按钮 -->
          <a-form-item>
            <a-button 
              @click="hide" 
              block
              class="later-btn"
            >
              Later
            </a-button>
          </a-form-item>
        </a-form>
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import { ref, onMounted, defineEmits } from 'vue';
import { message } from 'ant-design-vue';
import { Local } from '@/utils/storage';
import { getEmailVerificationCode as apiSendCode, verifyEmail as apiVerifyEmail, getMessageList } from '@/api/user';

const emit = defineEmits(['verified']);

// 控制弹窗显示
const visible = ref(false);

// 用户邮箱
const userEmail = ref('');

// 验证码
const verificationCode = ref('');

// 倒计时
const countdown = ref(0);
const isSending = ref(false);
const isVerifying = ref(false);

// 初始化
onMounted(() => {
  const userInfo = Local.get('userInfo');
  if (userInfo && userInfo.email) {
    userEmail.value = userInfo.email;
  }
  
  // 无感获取用户消息
  fetchUserMessages();
});

// 无感获取用户消息
const fetchUserMessages = async () => {
  try {
    const response = await getMessageList({
      page: 1,
      page_size: 10
    });
    
    if (response && response.data) {
      // 更新消息列表缓存
      Local.set('messageList', response.data);
    }
  } catch (error) {
    // 静默处理错误，不影响用户体验
    // 忽略CanceledError，这是正常的请求取消
  }
};

// 显示弹窗
const show = () => {
  visible.value = true;
  // 每次显示弹窗时刷新用户消息
  fetchUserMessages();
};

// 隐藏弹窗
const hide = () => {
  visible.value = false;
};

// 发送验证码
const sendVerificationCode = async () => {
  if (!userEmail.value) {
    message.error('Email address cannot be empty');
    return;
  }

  isSending.value = true;
  try {
    // 调用发送验证码API
    await apiSendCode(userEmail.value);
    message.success('Verification code has been sent to your email');
    
    // 开始倒计时
    countdown.value = 60;
    const timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(timer);
      }
    }, 1000);
  } catch (error) {
    // console.error('发送验证码失败:', error);
    // 不在这里显示错误消息，因为axios拦截器已经处理了错误提示
  } finally {
    isSending.value = false;
  }
};

// 验证邮箱
const verifyEmail = async () => {
  if (!verificationCode.value) {
    message.error('Please enter verification code');
    return;
  }

  isVerifying.value = true;
  try {
    // 这里应该调用验证邮箱的API
    await apiVerifyEmail(userEmail.value, verificationCode.value);
    
    
    // 更新本地存储中的用户信息
    const userInfo = Local.get('userInfo') || {};
    userInfo.is_email = 1;
    Local.set('userInfo', userInfo);
    
    message.success('Email verification successful');
    
    // 验证成功后再次获取用户消息
    await fetchUserMessages();
    
    // 通知父组件验证成功
    emit('verified');
    
    // 关闭弹窗
    hide();
  } catch (error) {
    message.error('Verification failed, please check if the code is correct');
  } finally {
    isVerifying.value = false;
  }
};

// 导出方法
defineExpose({
  show,
  hide
});
</script>

<style scoped>
.email-verification-modal :deep(.ant-modal-content) {
  border-radius: 12px;
  overflow: hidden;
}

.email-verification-modal :deep(.ant-modal-header) {
  background-color: #fff;
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.email-verification-modal :deep(.ant-modal-title) {
  color: #262626;
  font-size: 18px;
  font-weight: 600;
}

.email-verification {
  padding: 24px;
}

.description {
  margin-bottom: 32px;
  text-align: center;
}

.icon-container {
  margin-bottom: 20px;
}

.email-icon {
  font-size: 48px;
  color: #262626;
  background: #f5f5f5;
  padding: 16px;
  border-radius: 50%;
}

.title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #262626;
}

.desc-text {
  color: #595959;
  line-height: 1.6;
  margin-bottom: 0;
  font-size: 14px;
}

.verification-form {
  margin-top: 24px;
}

.email-input {
  border-radius: 8px;
  height: 40px;
  background-color: #f5f5f5;
  color: #262626;
  border: 1px solid #d9d9d9;
  
  &:disabled {
    background-color: #f5f5f5;
    color: #595959;
    border-color: #d9d9d9;
  }
}

.code-input {
  border-radius: 8px;
  height: 40px;
  border: 1px solid #d9d9d9;
  
  &:hover, &:focus {
    border-color: #262626;
  }
  
  &:where(.verification-code-input-focused) {
    border-color: #262626;
    box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.1);
  }
}

.send-code-btn {
  height: 40px;
  border-radius: 8px;
  font-weight: 500;
  background: #262626;
  border-color: #262626;
  color: #fff;
  
  &:hover {
    background: #434343;
    border-color: #434343;
  }
  
  &:disabled {
    background: #f5f5f5;
    border-color: #d9d9d9;
    color: #bfbfbf;
  }
}

.verify-btn {
  height: 44px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  margin-top: 12px;
  background: #262626;
  border-color: #262626;
  color: #fff;
  transition: all 0.3s ease;
  
  &:hover {
    background: #434343;
    border-color: #434343;
  }
  
  &:active {
    background: #000;
    border-color: #000;
  }
}

.later-btn {
  height: 44px;
  border-radius: 8px;
  font-size: 16px;
  color: #595959;
  border: 1px solid #d9d9d9;
  margin-top: 12px;
  transition: all 0.3s ease;
  
  &:hover {
    color: #262626;
    border-color: #262626;
  }
  
  &:active {
    color: #000;
    border-color: #000;
  }
}

:deep(.ant-form-item-label > label) {
  color: #262626;
  font-weight: 500;
}

:deep(.ant-input-affix-wrapper) {
  border-radius: 8px;
  
  &:hover, &:focus {
    border-color: #262626;
  }
  
  &:where(.verification-code-input-focused) {
    border-color: #262626;
    box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.1);
  }
}
</style> 

<!-- 
使用说明:

1. 引入组件:
   import EmailVerification from '@/components/EmailVerification.vue';

2. 在父组件中注册:
   components: {
     EmailVerification
   }

3. 在模板中使用:
   <template>
     <EmailVerification ref="emailVerificationRef" @verified="handleVerified" />
   </template>

4. 在脚本中使用:
   <script setup>
   import { ref } from 'vue';
   
   const emailVerificationRef = ref(null);
   
   // 显示邮箱验证弹窗
   const showEmailVerification = () => {
     emailVerificationRef.value.show();
   };
   
   // 处理验证成功事件
   const handleVerified = () => {
     console.log('邮箱验证成功');
     // 执行其他操作...
   };
   </script>

5. 组件方法:
   - show(): 显示邮箱验证弹窗
   - hide(): 隐藏邮箱验证弹窗

6. 组件事件:
   - verified: 当邮箱验证成功时触发

7. 功能说明:
   - 自动获取当前用户邮箱地址
   - 发送验证码到用户邮箱，并有60秒倒计时防止频繁发送
   - 验证用户输入的验证码
   - 验证成功后自动更新本地用户信息
   - 支持稍后验证，用户可以关闭弹窗
   - 响应式设计，适配不同屏幕尺寸

8. 依赖项:
   - ant-design-vue: UI组件库
   - @/utils/storage: 本地存储工具
   - @/api/user: 用户相关API
-->